package com.fengyuncx.tp.ali_push;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;

import androidx.annotation.NonNull;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.fengyuncx.tp.ali_push.utils.GlobalThreadManager;
import com.fengyuncx.tp.ali_push.utils.NotificationUtil;

import java.util.List;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** AliPushPlugin */
public class AliPushPlugin implements ActivityAware, FlutterPlugin, MethodCallHandler {
  public static final String TAG = "AliPushPlugin";


  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private static AliPushPlugin _instance;
  private MethodChannel channel;
  private Activity activity;
  /** 是否注册过服务 */
  private static boolean registed;
  /** 是否绑定了账号 */
  private boolean binded;
  private String account;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    _instance = this;
    Dlog.d(TAG, "onAttachedToEngine");
    channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "ali_push");
    channel.setMethodCallHandler(this);
  }

  // This static function is optional and equivalent to onAttachedToEngine. It supports the old
  // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
  // plugin registration via this function while apps migrate to use the new Android APIs
  // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
  //
  // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
  // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
  // depending on the user's project. onAttachedToEngine or registerWith must both be defined
  // in the same class.
  public static void registerWith(Registrar registrar) {
    Dlog.d(TAG, "registerWith");
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "ali_push");
    channel.setMethodCallHandler(new AliPushPlugin());
  }

  static Application application;
  static String appKey,secretKey;
  static CloudPushService pushService;
  /**
   * 初始化云推送通道
   */
  private static void init(Application application) {
    init(application, appKey, secretKey);
  }
  /**
   * 初始化云推送通道
   */
  public static void init(final Application application, String appKey, String secretKey) {
    AliPushPlugin.application = application;
    if(AliPushPlugin.appKey == null) {
      GlobalThreadManager.init(application);
      GlobalThreadManager.runInThreadPool(new Runnable() {
        @Override
        public void run() {
          NotificationUtil.init(application);
        }
      });
      AliPushPlugin.appKey = appKey;
      AliPushPlugin.secretKey = secretKey;
    }
    if(application == null){
      Dlog.e(TAG, "---initCloudChannel.error: applicationContext is null");
      return;
    }
    PushServiceFactory.init(application);
    pushService = PushServiceFactory.getCloudPushService();
    Dlog.e(TAG, "---initCloudChannel-register");
    pushService.register(application, appKey, secretKey, new CommonCallback() {
      @Override
      public void onSuccess(String response) {
        registed = true;
        Dlog.d(TAG, "init cloudchannel success");
        if(_instance != null && _instance.account != null){
          _instance.bindAccount(_instance.account);
        }
      }
      @Override
      public void onFailed(String errorCode, String errorMessage) {
        Dlog.d(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
      }
    });
  }
  /**
   * 初始化云推送通道
   */
  private static void initCloudChannel(Application application) {
    init(application);
  }

  /**
   * 推送服务绑定账号
   * @param account
   */
  private void bindAccount(String account){
    Dlog.d(TAG, "bindAccount");
    if(this.account != null && this.account.equals(account)){
      return;
    }
    this.account = account;
    if(registed) {
      pushService.bindAccount(account, new CommonCallback() {
        @Override
        public void onSuccess(String s) {
          Dlog.d(TAG, "cloudchannel---bindSuccess:" + s);
          binded = true;
        }

        @Override
        public void onFailed(String s, String s1) {
          Dlog.d(TAG, "cloudchannel---bindFailed:" + s + ", s1:" + s1);
        }
      });
    }else{
      initCloudChannel(application);
    }
  }

  /**
   * 推送服务解绑账号
   */
  private void unBindAccount(){
    Dlog.d(TAG, "unBindAccount");
    account = null;
    if(registed) {
      pushService.unbindAccount(new CommonCallback() {
        @Override
        public void onSuccess(String s) {
          Dlog.d(TAG, "cloudchannel---unBindSuccess:" + s);
          binded = false;
        }

        @Override
        public void onFailed(String s, String s1) {
          Dlog.d(TAG, "cloudchannel---unBindFailed:" + s + ", s1:" + s1);
        }
      });
    }else{
      initCloudChannel(application);
    }
  }
  /**将阿里推送消息桥接到flutter*/
  public static void onAliOnMessage(String method, String content){
    if(_instance != null) {
      _instance._onAliOnMessage(method, content);
    }
  }
  private void _onAliOnMessage(String method, Object arguments){
    if(channel != null){
      channel.invokeMethod(method, arguments);
    }
  }
  /**--------阿里推送相关end---------------------------------------------------------------------------------------------------------------*/


  /**--------平台消息通道相关start---------------------------------------------------------------------------------------------------------------*/

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    switch (call.method){
      case "bindAccount":
        Object arguments = call.arguments;
        if(arguments instanceof String){
          String account = (String) arguments;
          bindAccount(account);
        }
        break;
      case "unBindAccount":
        unBindAccount();
        break;
      case "getPlatformVersion":
        result.success("Android " + android.os.Build.VERSION.RELEASE);
        break;
      default:
        result.notImplemented();
        break;
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
    activity = binding.getActivity();
    if(activity != null) {
      application = activity.getApplication();
      GlobalThreadManager.init(application);
    }
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {

  }

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
    activity = binding.getActivity();
    if(activity != null) {
      application = activity.getApplication();
    }

  }

  @Override
  public void onDetachedFromActivity() {

  }
}
